package com.ruoyi.equ.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.equ.domain.EquAsset;
import com.ruoyi.equ.domain.FaultType;
import com.ruoyi.equ.domain.vo.EquRepairVos;
import com.ruoyi.equ.domain.vo.EquRepairUniVo;
import com.ruoyi.equ.domain.vo.SignAndStampVo;
import com.ruoyi.equ.mapper.EquAssetMapper;
import com.ruoyi.equ.service.IEquAssetService;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.equ.mapper.EquRepairMapper;
import com.ruoyi.equ.domain.EquRepair;
import com.ruoyi.equ.service.IEquRepairService;
import org.springframework.util.CollectionUtils;

/**
 * 维修工单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-11-05
 */
@Service
public class EquRepairServiceImpl implements IEquRepairService {
    @Autowired
    private EquRepairMapper equRepairMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private EquAssetMapper equAssetMapper;

    /**
     * 查询维修工单
     *
     * @param repairId 维修工单主键
     * @return 维修工单
     */
    @Override
    public EquRepair selectEquRepairByRepairId(Long repairId) {
        return equRepairMapper.selectEquRepairByRepairId(repairId);
    }

    /**
     * 查询维修工单列表
     *
     * @param equRepair 维修工单
     * @return 维修工单
     */
    @Override
    public List<EquRepair> selectEquRepairList(EquRepair equRepair) {
        return equRepairMapper.selectEquRepairList(equRepair);
    }

    /**
     * 查询维修工单列表（最近3条）
     *
     * @param equRepair
     * @return
     */
    @Override
    public List<EquRepairUniVo> selectEquRepairListThree(EquRepair equRepair) {
        //TODO 完成真正的获取【内容、金额】逻辑
        equRepair.setOrderStatus("已完成");//只查询已完成的
        List<EquRepair> list = equRepairMapper.selectEquRepairListThree(equRepair);
        if (list != null && !CollectionUtils.isEmpty(list)) {
            return list.stream().map(item -> {
                EquRepairUniVo vo = new EquRepairUniVo();
                BeanUtils.copyProperties(item, vo);
                if (item.getRepairExec() != null) {
                    JSONObject jsonObject = JSON.parseObject(item.getRepairExec());
                    //维修内容
                    if (jsonObject.containsKey("维修措施")) {
                        JSONArray repairArray = jsonObject.getJSONArray("维修措施");
                        List<String> repairList = new ArrayList<>();
                        for (int i = 0; i < repairArray.size(); i++) {
                            String repairItem = repairArray.getString(i);
                            if (repairItem != null && !repairItem.trim().isEmpty()) {
                                repairList.add(repairItem.trim());
                            }
                        }
                        //拼接"aa,bb"
                        String repairContent = String.join(",", repairList);
                        vo.setRepairContent(repairContent);
                    }
                    if (jsonObject.containsKey("维修费用")) {
                        BigDecimal repairCost = jsonObject.getBigDecimal("维修费用");
                        vo.setRepairCost(repairCost);
                    }
                }
                return vo;
            }).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    /**
     * 新增维修工单
     *
     * @param equRepair 维修工单
     * @return 结果
     */
    @Override
    public int insertEquRepair(EquRepair equRepair) {
        equRepair.setCreateTime(DateUtils.getNowDate());
        return equRepairMapper.insertEquRepair(equRepair);
    }

    /**
     * 修改维修工单
     *
     * @param equRepair 维修工单
     * @return 结果
     */
    @Override
    public int updateEquRepair(EquRepair equRepair) {
        equRepair.setUpdateTime(DateUtils.getNowDate());
        return equRepairMapper.updateEquRepair(equRepair);
    }

    /**
     * 批量删除维修工单
     *
     * @param repairIds 需要删除的维修工单主键
     * @return 结果
     */
    @Override
    public int deleteEquRepairByRepairIds(Long[] repairIds) {
        return equRepairMapper.deleteEquRepairByRepairIds(repairIds);
    }

    /**
     * 删除维修工单信息
     *
     * @param repairId 维修工单主键
     * @return 结果
     */
    @Override
    public int deleteEquRepairByRepairId(Long repairId) {
        return equRepairMapper.deleteEquRepairByRepairId(repairId);
    }

    @Override
    public Boolean addRepair(EquRepair equRepair) {
        try {
            //设置设备状态
            equRepair.setOrderStatus("待派工");
            int i = equRepairMapper.insertEquRepair(equRepair);
            return i > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public SignAndStampVo getSignAndStamp() {
        SignAndStampVo signAndStampVo = new SignAndStampVo();
        //获取审批人的签字以及所属部门的电子盖章
        //首先拿到登录人的id，通过id获取到个人信息（userId  deptId）
        Long userId = SecurityUtils.getUserId();
        //拿到登录人的信息
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        //拿到登录人的部门信息
        Long deptId = sysUser.getDeptId();
        //
        SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
        //拿到部门负责人的名字
        String leader = sysDept.getLeader();
        //通过名字，查询负责人的信息
        SysUser leaderUser = sysUserMapper.selectUserByUserName(leader);
        //获取负责人的签名
        String leaderSignature = leaderUser.getSignature();
        //获取登陆人所属部门的电子盖章
        String stamp = sysDept.getStamp();
        //再获取到 审批人的签字
        String signature = sysUser.getSignature();
        //设置信息，再返回
        signAndStampVo.setStamp(stamp);
        signAndStampVo.setleaderSign(leaderSignature);
        signAndStampVo.setSignature(signature);
//        sysUserService.selectUserByUserName()
        return signAndStampVo;
    }

    @Override
    public List<EquRepair> selectEquRepairListByMonth(EquRepair equRepair, int month) {
        // 获取到指定月份的维修工单数据
        List<EquRepair> equRepairList = equRepairMapper.selectEquRepairListByMonth(equRepair, month);

        return equRepairList;
    }

    @Override
    public List<FaultType> getFaultTypeData(Map<String, Object> params) {
        List<FaultType> faultTypes = new ArrayList<>();
        // 先拿到用户提交的品牌名字和型号
        String brand = (String) params.get("brand");
        String model = (String) params.get("model");
        EquAsset equAsset = new EquAsset();
        equAsset.setAssetBrand(brand);
        equAsset.setModelSpec(model);
        List<EquAsset> equAssets = equAssetMapper.selectEquAssetList(equAsset);

        for (EquAsset equAsset1 : equAssets) {
            EquRepair equRepair = new EquRepair();
            equRepair.setAssetId(equAsset1.getAssetId());
            List<EquRepair> equRepairList = equRepairMapper.selectEquRepairList(equRepair);
            if (equRepairList.size() > 0) {
                for (EquRepair equRepair1 : equRepairList) {
                    //获取到故障类型，并将其添加到集合中
                    String repairExec = equRepair1.getRepairExec();
                    Map<String, String> faultInfoMap = parseFaultInfo(repairExec);

                    // 注意：现在故障原因的key是"故障原因"而不是"原因"
                    String faultReasons = faultInfoMap.get("故障原因");
                    if (faultReasons != null && !faultReasons.isEmpty()) {
                        // 故障原因可能是多个用逗号分隔的原因
                        String[] reasons = faultReasons.split(",");
                        for (String faultType : reasons) {
                            faultType = faultType.trim();
                            if (!faultType.isEmpty()) {
                                System.out.println("故障原因：" + faultType);

                                // 查找是否已存在该故障类型
                                boolean found = false;
                                for (FaultType faultType1 : faultTypes) {
                                    if (faultType1.getFaultType().equals(faultType)) {
                                        // 存在则数量加1
                                        faultType1.setCount(faultType1.getCount() + 1);
                                        found = true;
                                        break;
                                    }
                                }

                                // 如果未找到，则添加新类型
                                if (!found) {
                                    FaultType faultType2 = new FaultType();
                                    faultType2.setFaultType(faultType);
                                    faultType2.setCount(1);
                                    faultTypes.add(faultType2);
                                }
                            }
                        }
                    }
                }
            }
        }

        // 计算百分比
        int totalCount = faultTypes.stream().mapToInt(FaultType::getCount).sum();
        for (FaultType faultType : faultTypes) {
            if (totalCount > 0) {
                faultType.setPercentage((double) Math.round(faultType.getCount() * 1000.0 / totalCount) / 10); // 保留一位小数
            } else {
                faultType.setPercentage(0.0);
            }
            System.out.println("故障类型：" + faultType.getFaultType() + " 数量：" + faultType.getCount() + " 百分比：" + faultType.getPercentage() + "%");
        }

        return faultTypes;
    }
    /**
     * 查询维修工单列表
     */
    @Override
    public List<EquRepairVos> selectEquRepairVoList(EquRepairVos repairVos) {
        return equRepairMapper.selectEquRepairVoList(repairVos);
    }
    /**
     * 获取维修记录详细信息
     * @param assetId
     * @return List<EquRepair>
     */
    @Override
    public List<EquRepair> getRepairsByAssetId(Long assetId) {
        return equRepairMapper.getRepairsByAssetId(assetId);
    }


    /**
     * 解析faultInfo JSON字符串
     *
     * @param faultInfo JSON字符串，格式如 {"故障现象":"运行报错","紧急程度":"紧急",...} {"负责人":"dwa","派工部门":"daw",...}
     * @return 包含所有键值对的Map
     */
    public Map<String, String> parseFaultInfo(String faultInfo) {
        System.out.println("faultInfo:" + faultInfo);
        Map<String, String> result = new HashMap<>();

        if (faultInfo != null && !faultInfo.isEmpty()) {
            try {
                // 按空格分割两个JSON对象
                String[] parts = faultInfo.split("(?<=\\})\\s+(?=\\{)");

                for (String part : parts) {
                    if (part.trim().startsWith("{") && part.trim().endsWith("}")) {
                        JSONObject obj = JSON.parseObject(part.trim());
                        for (Map.Entry<String, Object> entry : obj.entrySet()) {
                            String key = entry.getKey();
                            Object value = entry.getValue();

                            // 特别处理数组类型的数据
                            if (value instanceof JSONArray) {
                                JSONArray array = (JSONArray) value;
                                List<String> items = new ArrayList<>();
                                for (int i = 0; i < array.size(); i++) {
                                    items.add(array.getString(i));
                                }
                                result.put(key, String.join(",", items));
                            } else {
                                result.put(key, value.toString());
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                // 可以记录日志或抛出自定义异常
            }
        }

        return result;
    }


}
